<template>
  <search-table
    :page-pos="pagePos"
    :data="partList"
    :columns="partCol"
    :page.sync="queryParams.pageIndex"
    :size.sync="queryParams.pageSize"
    :total="partTotal"
    :loading="partListLoading"
    @queryFun="getNewData">
    <template slot="search">
      <Button type="primary" ghost class="md-add-jh" @click="showModal(null)">创建公共组件</Button>
      <Divider type="vertical" style="margin: 10px 0px 10px 10px;" />
      <Select filterable clearable v-model="queryParams.partType" @on-change="selectPart" placeholder="组件类型" style="margin-left: 15px;width: 150px">
        <Option v-for="item in COMPONENT_TYPE_OPTIONS" :key="item.value" :value="item.value">{{item.label}}</Option>
      </Select>
      <Input v-model.trim="queryParams.licenseType"  clearable placeholder="许可证类型" @on-change="searchPartName" style="width: 180px;margin-left: 15px" />
      <Input v-model.trim="queryParams.name"  clearable placeholder="公共组件名称" @on-change="searchPartName" style="width: 180px;margin-left: 15px" />
      <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshPartList()">
        <i class="el-icon-refresh-right" />
      </Button>
    </template>
    <!--创建镜像"-->

    <Modal v-model="modalData.show" :mask-closable="false" width="600"
           :title="`${ isAdd ? '创建公共组件' : '修改公共组件'}`"
           @on-visible-change="changeVisible"
    >
      <Form ref="formInline" :model="formInline" :rules="ruleInline" :label-width="120" style="width: 500px">
          <FormItem prop="name" label="组件名称" key="name">
            <Input clearable v-model="formInline.name" placeholder="请输入组件名称"></Input>
          </FormItem>
          <FormItem prop="version" label="版本号" key="version">
            <Input clearable v-model="formInline.version" placeholder="请输入版本号"></Input>
          </FormItem>
          <FormItem  label="类型" prop="partType" key="partType">
            <Select filterable transfer filterable clearable v-model="formInline.partType" placeholder="选择类型">
              <Option v-for="item in COMPONENT_TYPE_OPTIONS" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
        <!-- <FormItem prop="orgId" label="维护单位" key="orgId">
         <Cascader
           change-on-select
           :data="unitList"
           v-model="unitIds"
           @on-change="getUnitId"
           placeholder="请选择单位"
           clearable
         ></Cascader>
        </FormItem> -->
        <FormItem prop="modifier" label="责任人" key="modifier">
          <Input clearable v-model="formInline.modifier" placeholder="请输入责任人"></Input>
        </FormItem>
        <FormItem prop="url" label="关联URL" key="url">
          <Input clearable v-model="formInline.url" placeholder="请输入类似http://www.baidu.com格式网站"></Input>
        </FormItem>
          <FormItem prop="licenseType"  label="许可类型" key="licenseType">
            <Input clearable v-model="formInline.licenseType" placeholder="请输入许可证类型"></Input>
          </FormItem>
          <FormItem prop="supplier" label="开发单位" key="supplier">
            <Input clearable v-model="formInline.supplier" placeholder="请输入开发单位"></Input>
          </FormItem>
        <FormItem prop="protocolType" label="协议" key="protocolType">
          <Select filterable transfer filterable clearable v-model="formInline.protocolType" placeholder="选择协议">
            <Option :value="item.dictid" v-for="item in assetServiceTypeOptions" :key="item.dictid">{{ item.dictname }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="application" label="应用" key="application">
          <Select filterable transfer filterable clearable v-model="formInline.application" placeholder="选择应用">
            <Option :value="item" v-for="item in ASSET_APP_OPTIONS" :key="item">{{ item }}</Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer" class="footer">
        <Button @click="modalData.show = false">取消</Button>
        <Button @click="saveProductPart" :loading="modalData.loading" type="primary">确定</Button>
      </div>
    </Modal>
    <Modal
      v-model="detailModalData.show"
      title="公共组件详情"
      footer-hide
      class="my-modal">
      <div class="item-table">
        <p>
          <span class='label'>组件名称</span>
          <span>{{detailInfo.name}}</span>
        </p>
        <p>
          <span class='label'>版本</span>
          <span>{{detailInfo.version}}</span>
        </p>
        <p>
          <span class='label'>组件类型</span>
          <span>{{handlerSelectOptionShow(COMPONENT_TYPE_OPTIONS,detailInfo.partType).text}}</span>
        </p>
        <!-- <p>
          <span class='label'>维护单位</span>
          <span>{{detailInfo.orgName}}</span>
        </p> -->
        <p>
          <span class='label'>责任人</span>
          <span>{{detailInfo.modifier}}</span>
        </p>
        <p>
          <span class='label'>关联URL</span>
          <span>{{detailInfo.url}}</span>
        </p>
        <p>
          <span class='label'>许可证类型</span>
          <span>{{detailInfo.licenseType}}</span>
        </p>
        <p>
          <span class='label'>开发单位</span>
          <span>{{detailInfo.supplier}}</span>
        </p>
        <p>
          <span class='label'>协议</span>
          <span>{{detailInfo.protocolType}}</span>
        </p>
        <p>
          <span class='label'>应用</span>
          <span>{{detailInfo.application}}</span>
        </p>
      </div>
    </Modal>
    <component-deploy-pos ref="componentDeployPos"></component-deploy-pos>
    <component-relative-product ref="componentRelativeProduct"></component-relative-product>
  </search-table>
</template>
<script>
import encryption from '@/libs/encryption.js'
import resourcesReportedMixin from '@/mixin/resources-reported-mixin'
import pageTitle from '@/mixin/pageTitle';

import {
  queryProductPartList as queryProductPublicPart,
  addProductPart as addProductPublicPart,
  updateProductPart as updateProductPublicPart,
  deleteProductPart as deleteProductPublicPart
} from '../api/productPart'
import {ASSET_APP_OPTIONS, COMPONENT_TYPE_OPTIONS} from "../../paramsConfig";
import {handlerSelectOptionShow} from "../../common";
import ComponentDeployPos from "./componentDeployPos.vue";
import ComponentRelativeProduct from "./componentRelativeProduct.vue";
import {getAssetServiceType, getOrgUnitList} from "../logic/assetLogic";
import * as CommonFn from "../../common";
import {validateSite} from "../../../../libs/reg";
export default {
  components: {ComponentRelativeProduct, ComponentDeployPos},
  mixins: [resourcesReportedMixin,pageTitle],
  props: {
    productId: {
      type: String,
      default: ''
    },
    pagePos:{
      type:String,
      default: 'top'
    },
  },
  data () {
    return {
      ASSET_APP_OPTIONS,
      assetServiceTypeOptions:[],
      unitIds:[],
      unitList:[],
      vendorList:[],
      assetCategoryList:[],
      partListLoading:false,
      COMPONENT_TYPE_OPTIONS,
      partTotal:0,
      formInline: {
       name:'',
        partType:undefined,
        version:'',
        orgId: '',
        people:'',
        url:'',
        licenseType: '',
      },
      ruleInline: {
        name: [
          { required: true, message: '组件名称不能为空', trigger: 'blur,change' }
        ],
        partType: [
          { required: true, type:'number', message: '组件类型不能为空', trigger: 'blur,change' }
        ],
        orgId: [
          { required: true, message: '维护单位不能为空', trigger: 'change' }
        ],
        version: [
          { required: true, message: '版本号不能为空', trigger: 'blur,change' }
        ],
        licenseType:[
          { required: true, message: '许可证类型不能为空', trigger: 'blur,change' }
        ],
        url:[
          {validator:validateSite,trigger:'blur'}
        ],
      },
      modalData: {
        show: false,
        loading: false
      },
      isAdd: false,
      upgradeType: 'add',
      isUpgrade: false,
      file: {},
      optionList: [],
      detailModalData: {
        show: false
      },
      detailInfo: {},

      queryParams:{
        pageIndex:1,
        pageSize:10,
        isPublic:'Y'
      },
      // 用户信息
      USER_ID: '',
      isRootDesinger: '',
      distributed: false,
      partList: [],
      partCol: [
        {
          title:'组件名称',
          key:'name',
          tooltip:true
        },
        {
          title:'版本',
          key:'version'
        },
        {
          title:'组件类型',
          key:'partType',
          render:(h,params)=>{
            let obj = handlerSelectOptionShow(COMPONENT_TYPE_OPTIONS,params.row.partType)
            return h('Tag',{
            props:{
              color:obj.color,
            }
            }, obj.text)
          }
        },
        // {
        //   title:'维护单位',
        //   key:'orgName',
        //   tooltip:true
        // },
        {
          title:'关联url',
          key:'url',
          width:140,
          tooltip: true,
        },
        {
          title:'风险评分',
          key:'lastInheritedRiskScore'
        },
        {
          title:'漏洞数',
          key:'vulnerabilities'
        },
        {
          title:'许可证类型',
          key:'licenseType',
        },
        {
          title: '操作',
          width: 280,
          slot: 'action',
          opList: [
            {
              txt: '详情',
              on:{
                click:(data,e) => {
                  this.detailModalData.show = true
                  this.detailInfo = data
                }
              },
            },
            {
              txt: '修改',
              on:{
                click:(data,e) => {
                  this.showModal(data)
                }
              },
            },
            {
              txt: '删除',
              tooltip: true,
              type: 'delete',
              title: '确定要删除这个组件吗？',
              on:{
                click:(data,e) => {
                  this.deleteItem(data.id)
                }
              },
            },
            {
              txt: '关联产品',
              on:{
                click:(data,e) => {
                  this.$refs.componentRelativeProduct.openModal(data);
                }
              },
            },
            {
              txt: '部署位置',
              on:{
                click:(data,e) => {
                  this.$refs.componentDeployPos.openModal(data);
                }
              },
            },
          ]
        },
      ]
    }
  },
  computed: {

  },
  watch: {


  },
  created () {
    // 获取用户id
    let November = sessionStorage.getItem('November')
    November = JSON.parse(encryption.SelfUseDecrypt(November))
    this.USER_ID = November.userId
    this.isRootDesinger = November.isRootDesinger
    this.distributed = November.distributed
    // this.distributedRange = this.$store.state.user.distributedRange
  },
  mounted () {
    let getPage = this.$route.query.page ? parseInt(this.$route.query.page) : 1
    this.queryParams.pageIndex = getPage
    this.getNewData()

  },
  methods: {
    handlerSelectOptionShow,
    getNewData(isRefresh){
      // 列表
      if (!isRefresh) { // 非刷新操作才需要展示等待中的画面
        this.partListLoading = true
      }
      queryProductPublicPart(this.queryParams)
        .then(res => {
          if (res.code == 1) {
            this.partTotal =res.data.total;
            this.partList = res.data.items
          }
          this.partListLoading = false
        })
        .catch(err => {
          this.partListLoading = false
        })
    },
    getUnitId(val){
      const id =  val.length?val[val.length-1]:'';
      this.formInline.orgId = id;
      this.$refs.formInline.validateField('orgId');
    },
    selectPart(){
      this.queryParams.pageIndex = 1;
      this.getNewData();
    },
    searchPartName(){
      this.queryParams.pageIndex = 1;
      this.getNewData();
    },
    refreshPartList(){
      this.queryParams = {
        pageIndex:1,
        pageSize:10,
        isPublic: 'Y'
      }
      this.getNewData()
    },
    // 保存数据
    saveProductPart() {
      this.$refs.formInline.validate(valid => {
        if (valid) {
          this.modalData.loading = true
          let apiName = this.isAdd ? addProductPublicPart : updateProductPublicPart
          if (this.isAdd) { // 创建操作确认把id删掉，避免造成错误
            delete this.formInline.id
            this.formInline.isPublic = 'Y';
          }
          apiName(this.formInline).then(({ code, message }) => {
            if (code !== 1) {
              this.$Message.warning(message)
              return
            }
            // 创建成功
            this.$Message.success(`${this.isUpgrade ? '升级' : this.isAdd ? '创建' : '修改'}组件成功`)
            this.getNewData()
            this.modalData.show = false
          }).catch(() => {
            this.$Message.error(`${this.isUpgrade ? '升级' : this.isAdd ? '创建' : '修改'}组件异常`)
          }).finally(() => {
            this.modalData.loading = false
          })
        }
      })
    },

// 删除组件
    deleteItem(id) {
      deleteProductPublicPart([id]).then(({ code, message }) => {
        if (code !== 1) {
          this.$Message.warning(message)
          return
        }
        this.$Message.success(`删除成功`)
        // 删除后展示当前页，当前页没有数据展示前一页
        this.queryParams.pageIndex = (this.partList.length === 1 && this.queryParams.pageIndex > 1) ?
          this.queryParams.pageIndex - 1 : this.queryParams.pageIndex;
        this.getNewData();
      }).catch(() => {
        this.$Message.error(`删除组件异常`)
      })
    },
    // 打开模态框
    async showModal(data) {
      this.isAdd = !data
      this.modalData.show = true
      if(!this.unitList.length) {
        await getOrgUnitList(this,'unitList');
      }
      if(!this.assetServiceTypeOptions.length){
        await  getAssetServiceType(this,'assetServiceTypeOptions')
      }
      let obj = data || {}
      this.formInline = Object.assign({ productId: this.productId }, obj)
      this.$nextTick(() => {
        let resSoftware = obj.resSoftware || {}
        let { fileId, language, type, fileName, id } = resSoftware
        if (fileId) {
          this.$refs.fileUpload && this.$refs.fileUpload.showDefaultList({fileName, filePath: fileId})
        } else {
          this.$refs.fileUpload && this.$refs.fileUpload.showDefaultList(null)
        }
        this.unitIds =  CommonFn.getIdsFromID(obj.orgId,this.unitList);
        this.formInline = {...data};
        // this.$set(this.formInline, 'packageType', type)
        // this.$set(this.formInline, 'language', language)
        // this.$set(this.formInline, 'relationId', obj.productPartRelation ? obj.productPartRelation.id : '')
        // this.$set(this.formInline, 'softwareId', id)
        // this.$set(this.formInline, 'fileId', fileId)
        // this.$set(this.formInline, 'softwareFileName', fileName)
      })
    },
    // 打开关联组件的模态框，初始化数据
    changeVisible(type) {
      if (!type) {
        this.$refs.formInline.resetFields()
        this.upgradeType = 'add'
        this.modalData.loading = false
      }
    },
  },
  beforeDestroy () {

  }
}
</script>
<style scoped>
#quesDetail {
  display: table;
  width: 100%;
  border: 1px solid var(--table-border);
  table-layout: fixed;
  word-break: break-all;
}
#quesDetail p {
  display: table-row;
  line-height: 36px;
  text-align: center;
}
#quesDetail p span {
  display: table-cell;
  border-bottom: 1px solid var(--table-border);
}
.ios-alert {
  /* position: absolute;
        top: -44px;
        right: -404px; */
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
.too {
  position: absolute;
  left: 113px;
  top: -1px;
}
.my-form-item{
  display: flex;
}
.item-table {
  display: table;
  width: 100%;
  border: 1px solid #eee;
  table-layout: fixed;
  word-break: break-all;
}
.item-table p {
  display: table-row;
  line-height: 36px;
  text-align: center;
}
.item-table p span {
  display: table-cell;
  border-bottom: 1px solid #eee;
}
</style>
